<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="../../../css/aui.css" />
        <script src="../../../script/jquery.js"></script>
        <script src="../../../CommonTool/commonNetWork.js"></script>
    </head>
    <style>
        .ImageInfoBody {
            max-width: 8rem;
            min-width: 6rem;
            height: 8rem;
        }
        .marginBody {
            margin-top: 2%;
        }
        .NarrateBody {
            margin-top: 2%;
            max-width: 60vw;
            min-width: 12rem;
            height: 33vw;
        }
        .InfoContent {
            margin-top: 75%;
            margin-left: 6%;
        }
        #ThingOne {
            width: 100%;
            height: 10rem;
            margin-left: 1%;
            margin-top: 2%;
            background-size: 100%;
        }
        @media (min-width: 1240px) and (orientation: landscape) {
            .row-margin {
                margin-top: 1%;
            }
        }
    </style>
    <body>
        <header class="aui-bar aui-bar-nav" id="aui-header">
            <div class="aui-pull-left aui-btn" onclick="close_win();">
                <span class="aui-iconfont aui-icon-left"></span>返回
            </div>
            <div class="aui-title">基础-初级-视线训练-视线维持</div>
        </header>

        <div class="aui-grid marginBody">
            <div id="BlounceBody">
                <div class="aui-row row-margin" style="height: 45vw">
                    <div class="aui-col-xs-1"></div>
                    <div class="aui-col-xs-10" style="height: 100%">
                        <img src="http://172.16.32.194/social/basic/8-视线训练/提示.png" alt="" id="TipBody" />
                    </div>
                </div>
            </div>

            <div id="eleBodyVisible" style="display: none">
                <div class="aui-row row-margin" style="height: 45vw">
                    <div class="aui-col-xs-1"></div>
                    <div class="aui-col-xs-10" style="height: 100%">
                        <video controls class="NarrateBody" style="width: 100%; height: 100%; object-fit: cover">
                            <source
                                type="video/mp4"
                                src="http://172.16.32.194/social/basic/8-视线训练/3-视线维持/4.mp4"
                            />
                        </video>
                    </div>
                </div>
            </div>

            <div class="aui-row">
                <div class="aui-col-xs-4"></div>
                <div class="aui-col-xs-4">
                    <div class="aui-btn aui-btn-primary StyleButton" id="SightstartButton">开始录制</div>
                    <div class="aui-btn aui-btn-primary StyleButton" id="SightstopButton" style="display: none">
                        结束录制
                    </div>
                </div>
            </div>
        </div>

        <!-- ✅ 修正后的 footbar 部分 -->
        <div class="footbar">
            <div class="barLeft" onclick="toggleMenu()">第四关</div>

            <div class="barCenter">
                <div id="InitialButton" style="float: left; margin-left: 4%" onclick="InitialClick()">
                    <img id="passImg" src="http://172.16.32.194/commonButton/加号.png" alt="" />
                </div>
                <div
                    id="InitialButton1"
                    style="float: left; margin-left: 4%; display: none"
                    onclick="ShowInitialClick()"
                >
                    <img id="passImg" src="http://172.16.32.194/commonButton/减号.png" alt="" />
                </div>
                <div id="InitialButton4" style="float: left; margin-left: 4%; display: none" onclick="ResetClick()">
                    <img
                        style="width: 2rem; height: 2rem; margin-top: 6%"
                        src="http://172.16.32.194/commonButton/刷新1.png"
                        alt=""
                    />
                </div>
            </div>

            <div class="barright">
                <img
                    src="http://172.16.32.194/commonButton/next1.png"
                    alt=""
                    class="BarBottom"
                    onclick="go_forward();"
                />
            </div>
            <div class="barright">
                <img
                    src="http://172.16.32.194/commonButton/prev1.png"
                    alt=""
                    class="BarBottom"
                    onclick="next_forward();"
                />
            </div>
        </div>

        <!-- 通过 -->
        <div class="backdrop_bg" id="backdropPass">
            <audio src="http://172.16.32.194/commonButton/鼓掌音效.mp3" id="audioBodyPass"></audio>
            <div class="backdrop_contentPasseGif"></div>
        </div>

        <div class="menu" id="menu">
            <div class="menu-item" onclick="goto_page(1)">第一关</div>
            <div class="menu-item" onclick="goto_page(2)">第二关</div>
            <div class="menu-item" onclick="goto_page(3)">第三关</div>
            <div class="menu-item" onclick="goto_page(4)">第四关</div>
            <div class="menu-item" onclick="goto_page(5)">第五关</div>
        </div>
    </body>
</html>
<script>
    var isRecording = true;
    var token = "";
    var userid = "";
    var currentTimestamp = "";
    var operationName = "";
    var additionalInfo = "";
    var groupId = "";
    var scene = "基础";
    var sceneLevel = "初级";
    var courseType = "视线训练";
    var classSort = "4";
    var moodType = "";
    var remarks = "视线维持";
    var classType = "学习";
    var startButton = document.getElementById("SightstartButton");
    var stopButton = document.getElementById("SightstopButton");
    let mediaRecorder;
    let chunks = [];
    let blob;
    let videoStream;
    var Nowdate = "";
    var NowdateString = "";
    let SightfileName = "";
    apiready = function () {
        token = api.pageParam.token;
        userid = api.pageParam.uid;
        groupId = api.pageParam.groupId;
        currentTimestamp = Date.now();
        operationName = "ing";
        additionalInfo = "";
        CommonNetWork();
        isRecording = true;
        //  const gifImage = document.getElementById('ThingOne');
        //  gifImage.src = `${gifImage.src}?nocache=${new Date().getTime()}`;
        //      let index = 0;
        // const interval = setInterval(() => {
        //   if (index < textToAnimate.length) {
        //     // 创建一个新的span元素来包裹每个字
        //     const charSpan = document.createElement('span');
        //     charSpan.textContent = textToAnimate[index];
        //     // 添加跳动动画类名
        //     charSpan.classList.add('jump-animation');
        //     // 将包含字的span元素添加到textDisplay中
        //     textDisplay.appendChild(charSpan);
        //     index++;
        //   } else {
        //     clearInterval(interval);
        //   }
        // },200); // 可以调整这个时间间隔来控制跳动速度
    };
    function InitialClick() {
        document.getElementById("InitialButton").style.display = "none";
        document.getElementById("InitialButton1").style.display = "block";
        document.getElementById("InitialButton4").style.display = "block";
    }
    function ShowInitialClick() {
        document.getElementById("InitialButton").style.display = "block";
        document.getElementById("InitialButton1").style.display = "none";
        document.getElementById("InitialButton4").style.display = "none";
    }
    function ResetClick() {
        history.go(0);
    }
    async function getMediaStream() {
        try {
            // 有权限的情况下获取媒体流
            videoStream = await navigator.mediaDevices.getUserMedia({
                video: { facingMode: "user", width: 1920, height: 1080 },
                audio: {
                    echoCancellation: true, // 启用回声消除
                },
            });
            mediaRecorder = new MediaRecorder(videoStream);
            return videoStream;
        } catch (err) {
            api.alert("获取媒体流失败:", err);
        }
        // try {
        //   // 首先检查并请求权限
        //   if (!await requestPermissions()) {
        //     return; // 如果没有权限，不继续执行
        //   }

        //   // 有权限的情况下获取媒体流
        //   videoStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: false });
        //   mediaRecorder = new MediaRecorder(videoStream);
        //   return videoStream;
        // } catch (err) {
        //   api.alert('获取媒体流失败:', err);
        // }
    }
    // 开始录制
    startButton.addEventListener("click", async () => {
        alert("开始录制");
        document.getElementById("eleBodyVisible").style.display = "block";
        document.getElementById("BlounceBody").style.display = "none";
        startButton.style.display = "none";
        stopButton.style.display = "block";
        // document.getElementById('ThingTwo').style.display='none'
        // setTimeout(() => {
        // document.getElementById('ThingOne').style.display="none"
        // document.getElementById('ThingTwo').style.display='block'
        // }, 4000);
        // setTimeout(()=>{
        //     document.getElementById('ThingTwo').style.display='none'
        // },8000)
        videoStream = await getMediaStream();
        mediaRecorder.start();
        mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
                chunks.push(event.data);
            }
        };
        currentTimestamp = Date.now();
        operationName = "ing";
        additionalInfo = "sight";
        CommonNetWork();
        //开始录制这里获取时间
        // Nowdate = new Date();
        // const year = Nowdate.getUTCFullYear();
        // const month = (Nowdate.getUTCMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以加1
        // const day = Nowdate.getUTCDate().toString().padStart(2, "0");
        // const hours = (Nowdate.getUTCHours() + 8).toString().padStart(2, "0");
        // const minutes = Nowdate.getUTCMinutes().toString().padStart(2, "0");
        // const seconds = Nowdate.getUTCSeconds().toString().padStart(2, "0");
        // 组合成字符串
        // NowdateString = `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
        //切换到结束录制按钮
        isRecording = false;
        // 自动播放
        const video = document.querySelector(".NarrateBody");
        video.play();
    });
    // 停止录制并处理录制数据
    stopButton.addEventListener("click", () => {
        mediaRecorder.stop();
        mediaRecorder.onstop = () => {
            blob = new Blob(chunks, { type: "video/mp4" });
            // 上传视频数据
            uploadVideo(blob);
            chunks = [];
            isRecording = true;
            startButton.style.display = "block";
            stopButton.style.display = "none";
        };
    });
    function uploadVideo(blob) {
        const blobChunk = blob;
        var chunkSize = 1024 * 1024;
        let start = 0; // 从0开始切片
        let count = 1; //从1开始
        var totalPieces = Math.ceil(blobChunk.size / chunkSize); //总数

        while (start < blobChunk.size) {
            var end = start + chunkSize;
            if (end > blobChunk.size) {
                //小于1M也传
                end = blobChunk.size;
            }
            uploadChunk(blobChunk.slice(start, end), count, totalPieces, end == blobChunk.size);
            start += chunkSize;
            count++;
        }
    }
    function uploadChunk(chunk, count, totalPieces, bLast) {
        ImitatefileName =
            userid +
            "—" +
            scene +
            "—" +
            sceneLevel +
            "—" +
            courseType +
            "—" +
            classType +
            "—" +
            classSort +
            "—" +
            groupId +
            "—" +
            currentTimestamp +
            ".mp4";
        var formData = new FormData();
        formData.append("audioFile", chunk);
        formData.append("sliceNumber", count);
        formData.append("totalSlices", totalPieces);
        formData.append("fileName", ImitatefileName);
        formData.append("userid", userid);
        // 使用原生的fetch API示例（可替换为XMLHttpRequest等方式）
        fetch(CommonUrl + "/test/uploadSlice", {
            method: "post",
            headers: {
                Authorization: `Bearer ${token}`,
            },
            body: formData,
        })
            .then((res) => {
                // 上传成功后的处理
                if (bLast) {
                    alert("上传成功");
                }
                // alert(JSON.stringify(res));
            })
            .catch((res) => {
                // 上传失败后的处理
                alert("上传失败");
                // alert(JSON.stringify(res));
            });
    }
    //上传本地视频的时候用到这个方法
    function CallVideo() {
        var has = hasPermissionObj("storage");
        if (!has || !has[0] || !has[0].granted) {
            api.confirm(
                {
                    title: "提醒",
                    msg: "没有获得 " + "本地存储" + " 权限\n是否前往设置？",
                    buttons: ["去设置", "取消"],
                },
                function (ret, err) {
                    if (1 == ret.buttonIndex) {
                        reqPermission("storage");
                    }
                }
            );
            return false;
        }
    }
    function reqPermission(one_per, callback) {
        var perms = new Array();
        if (one_per) {
            perms.push(one_per);
        } else {
            perms = ["storage"];
        }
        api.requestPermission(
            {
                list: perms,
                code: 100001,
            },
            function (ret, err) {
                if (callback) {
                    callback(ret);
                    return;
                }
                var str = "请求结果：\n";
                str += "请求码: " + ret.code + "\n";
                str += '是否勾选"不再询问"按钮: ' + (ret.never ? "是" : "否") + "\n";
                str += "请求结果: \n";
                var list = ret.list;
                for (var i in list) {
                    str += list[i].name + "=" + list[i].granted + "\n";
                }
                console.log(JSON.stringify(ret));
            }
        );
    }

    function hasPermissionObj(one_per) {
        var perms = new Array();
        if (one_per) {
            perms.push(one_per);
        } else {
            perms = ["storage"];
        }
        var rets = api.hasPermission({
            list: perms,
        });
        if (!one_per) {
            return;
        }
        return rets;
    }

    function close_win() {
        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "out";
        api.openWin({
            name: "SubsetMenu-Basics",
            url: "../../SubsetMenu-Basics.html",
            pageParam: {
                uid: userid,
                token: token,
            },
            reload: true,
        });
    }
    function go_forward() {
        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "";
        CommonNetWork();
        api.openWin({
            name: "SightTraining5",
            url: "./SightTraining5.html",
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
        });
    }
    function next_forward() {
        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "";
        CommonNetWork();
        api.openWin({
            name: "SightTraining3",
            url: "./SightTraining3.html",
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
        });
    }
    function goto_page(number) {
        const pages = ["SightTraining1", "SightTraining2", "SightTraining3", "SightTraining4", "SightTraining5"];

        var name = pages[number - 1];
        var url = "./" + name + ".html";

        document.querySelectorAll("audio").forEach((audio) => audio.pause());

        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "";
        CommonNetWork();
        api.openWin({
            name: name,
            url: url,
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
        });
    }
    function toggleMenu() {
        var menu = document.getElementById("menu");
        if (menu.style.display === "none" || menu.style.display === "") {
            menu.style.display = "block";
        } else {
            menu.style.display = "none";
        }
    }
</script>
